package com.sunday.player.util;

import java.util.ArrayList;
import java.util.List;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.database.Cursor;
import android.os.Handler;
import android.provider.BaseColumns;
import android.provider.MediaStore;
import android.provider.MediaStore.Audio.AudioColumns;
import android.provider.MediaStore.MediaColumns;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ListView;

import com.sunday.player.R;
import com.sunday.player.basicActivity;
import com.sunday.player.adapter.adapter_folder;
import com.sunday.player.domain.domain_folder;
import com.sunday.player.domain.musicData;
import com.sunday.player.domain.musiclist;
/**
 * 선택한 폴더에서 mp3 목록을 구성한다
 * @author user
 *
 */
public class searchMusicfile {
    private final String TAG = this.getClass().getSimpleName();
    private basicActivity context;
    private adapter_folder<domain_folder> adapter_folder;
    private List<domain_folder> list_list;
    private fileManager fileManager;
    private Handler mHandler = new Handler();
    
    
    public searchMusicfile(basicActivity con) {
	this.context = con;
	fileManager = new fileManager();
	list_list = new ArrayList<domain_folder>();
    }
    public static final String[] SONG_PROJECTION = new String [] {
		AudioColumns._ID,
		AudioColumns.DATA,        // 풀패스 
		AudioColumns.DISPLAY_NAME, // 파일이름
		AudioColumns.TITLE,
		AudioColumns.DURATION,
		AudioColumns.ALBUM_ID,
		AudioColumns.ALBUM,
		AudioColumns.TRACK,   // 트랙넘버 
		AudioColumns.YEAR,
		AudioColumns.ARTIST_ID,
		AudioColumns.ARTIST,
	};
    
    
    /**
     * 얼럿박스로 폴더열기 
     */
    public void openFolder(){
	context.showProgerssBar(context.getResourseString(R.string.progress_mp3Search));
	new Thread(new Runnable() {
	    
	    @Override
	    public void run() {
		
		if(!fileManager.isSDCARD_Mounted()){
		    mHandler.post(showfolder);
		    return;
		}
		
		int count = 0;
		String[] folderlist = fileManager.getFolder(fileManager.SDCARDPATH.toString());
		for(String folderpath : folderlist){
		    playerControl.Trace_i("folderpath = "+folderpath, TAG);
		    count = fileManager.getFolderAllCount(fileManager.SDCARDPATH.toString()+"/"+folderpath, true);
		    if(count > 0){
			list_list.add(new domain_folder(folderpath,fileManager.SDCARDPATH.toString()+"/"+folderpath,count));
		    }
		}
		
		getMp3();
		adapter_folder = new adapter_folder<domain_folder>(context, 0, list_list);
		context.hideProgressBar(true);
		
		mHandler.post(showfolder);
	    }
	}).start();
	
	
    }
    /**
     * 자동으로 MP3 파일 DB에 추가 
     */
    public void searchAddMP3(){
	context.showProgerssBar(context.getResourseString(R.string.progress_mp3Search));
	new Thread(new Runnable() {
	    
	    @Override
	    public void run() {
		
		if(!fileManager.isSDCARD_Mounted()){
		    mHandler.post(showfolder);
		    return;
		}
		musiclist listitem = new musiclist("MP3", false, getMp3());
	
		context.getdBcontroler().list_make(listitem);
		context.hideProgressBar(true);
		//mHandler.post(showfolder);
	    }
	}).start();
    }
    Runnable showfolder  = new Runnable() {
	    
	    @Override
	    public void run() {
		AlertDialog.Builder showFolder = new AlertDialog.Builder(context);
        		if(list_list.size() == 0){
        		    showFolder.setMessage(context.getResourseString(R.string.Message_nomp3File));
        		    showFolder.setPositiveButton(context.getResourseString(R.string.alertBox_ok),null);
        		}else{
        		    
        			LayoutInflater LI = (LayoutInflater)context.getLayoutInflater();
        			View setview = LI.inflate(R.layout.alert_listview, null);
        			ListView LV = (ListView)setview.findViewById(R.id.listView1);
        			LV.setAdapter(adapter_folder);
        			showFolder.setView(setview);
        			
        			showFolder.setPositiveButton(context.getResourseString(R.string.alertBox_ADD), new OnClickListener() {
        			    
        			    @Override
        			    public void onClick(DialogInterface dialog, int which) {
        				boolean isTotal = true;
        				for(domain_folder folder : list_list){
        				    if(folder.isCheck()){
        					isTotal = false;
        					List<String> mp3list = fileManager.getFolderAllList(folder.getPath(), true);
        					for(String title : mp3list){
        					    playerControl.Trace_i(title, TAG);
        					}
        				    }
        				}
        				if(isTotal){
        				    
        				}
        				
        			    }
        			});
        			
        		}
		showFolder.create().show();
	    }
	};
	
	/**
	 * is_music=1  인 mp3 파일을 불러온다
	 * 나중에 http://www.androidpub.com/2396154 폴더별로 불러오기 참고할것
	 */
	public List<musicData> getMp3(){
		
	    List<musicData> mp3data = new ArrayList<musicData>();
	    
	    String[] args = new String[1];
		args[0] = "%<unknown>%";
		Cursor c =	context.getContentResolver().query(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
			SONG_PROJECTION, "(artist NOT LIKE ?) AND is_music=1", args,null);
		if(c.moveToFirst()) {
			do {
				try {
					playerControl.Trace_i("------------------------------------", TAG);
					
					for(int a= 0 ; a < c.getColumnCount() ; a++){
						playerControl.Trace_i(a+" mp3 = "+c.getColumnName(a)+" = "+c.getString(a), TAG);
					}
					musicData item = new musicData(c);
					mp3data.add(item);
					
				} catch (Exception e) {
					e.printStackTrace();
				}
			} while(c.moveToNext());
		}
		c.close();
		return mp3data;
	}
    
}
